package com.tsing.service.impl;

import com.tsing.common.result.Result;
import com.tsing.mapper.AdUserMapper;
import com.tsing.mapper.impl.AdUserMapperImpl;
import com.tsing.pojo.entity.AdUser;
import com.tsing.service.AdUserService;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @author 吴阳基
 * @datetime 2023/12/13 11:28
 */
public class AdUserServiceImpl implements AdUserService {
    private AdUserMapper userMapper = new AdUserMapperImpl();

    @Override
    public Integer authenticateUser(String username, String password) {
        AdUser user = userMapper.getUserByUsername(username);

        //使用随机数生成盐
//        SecureRandom random = new SecureRandom();
//        byte[] saltBytes = new byte[16];
//        random.nextBytes(saltBytes);
//        String salt = Base64.getEncoder().encodeToString(saltBytes);

        if (user == null) {
            return 4; // 用户不存在，返回 4
        }

        // 获取数据库中存储的盐
        String salt = user.getSalt();

        // 对密码进行加盐和MD5加密
        String saltedPassword = password + salt;
        String hashedPassword;
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] hashedPasswordBytes = sha256.digest(saltedPassword.getBytes(StandardCharsets.UTF_8));
            hashedPassword = Base64.getEncoder().encodeToString(hashedPasswordBytes);
        } catch (NoSuchAlgorithmException e) {
            // 处理算法不支持的异常 算法错误误，返回 2
            return 2;
        }

        // 验证密码是否匹配
        if (!hashedPassword.equals(user.getPassword())) {
            //密码不正确匹配，返回 3
            return 3;
        }

        // 验证通过，返回成功结果 9
        return 9;
    }
}
